package com.genghis.ptas.question.dao.impl;

import com.genghis.core.page.dao.PageDao;
import com.genghis.ptas.question.dao.AnswerDao;
import com.genghis.ptas.question.entity.Answer;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: gaoyang
 * To change this template use File | Settings | File Templates.
 */
@Repository("answerDao")
public class AnswerDaoImpl extends PageDao implements AnswerDao {

    @Override
    public void addAnswer(Answer answer) {
        String sql = "INSERT INTO answer (answer_content, user_id, answer_date, is_adopted, question_id) " +
                " VALUES(:answerContent, :userId, :answerDate, :isAdopted, :questionId)";
        getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(answer));
    }

    @Override
    public void editAnswer(Answer answer) {
        String sql = "UPDATE answer SET answer_content = :answerContent, user_id = :userId, " +
                " answer_date = :answerDate, is_adopted = :isAdopted, question_id = :questionId WHERE id = :id ";
        getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(answer));
    }

    @Override
    public void delAnswerByIds(String ids) {
        String sql = "DELETE FROM answer WHERE id in(" + ids + ")";
        getJdbcTemplate().update(sql);
    }

    @Override
    public void delAnswerByQuestionId(String ids) {
        String sql = "DELETE FROM answer WHERE question_id in(" + ids + ")";
        getJdbcTemplate().update(sql);
    }

    @Override
    public Answer findAnswerById(int id) {
        StringBuilder sql = getAnswerSql();
        sql.append(" AND a.id=?");
        return getJdbcTemplate().queryForObject(sql.toString(), new BeanPropertyRowMapper<Answer>(Answer.class), id);
    }

    @Override
    public List<Answer> findAllAnswerByQuestionId(Integer questionId) {
        String sql = "SELECT a.*,su.`user_name` FROM answer a,sys_user su where a.`user_id`=su.id and a.question_id = ?";
        return getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Answer>(Answer.class), questionId);
    }

    @Override
    public List<Answer> findNewestAnswerByQuestionId(int id) {
        String sql = "SELECT * FROM answer WHERE question_id = ? ORDER BY answer_date DESC";
        return getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Answer>(Answer.class), id);
    }

    public StringBuilder getAnswerSql() {
        return new StringBuilder("select * from answer a where 1=1 ");
    }
}
